<template>
  <div class="vehicle-dispatch bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">应急处置方案管理</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchVehicles" @reset="resetSearch">
      </QueryForm>
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <!-- <el-button type="primary" @click="openAddDialog"
        class="bg-primary text-primary-foreground px-4 py-2 rounded">新增</el-button>
      <el-button type="danger" @click="deleteSelected"
        class="bg-destructive text-destructive-foreground px-4 py-2 rounded">删除</el-button>
      <el-button @click="openImportDialog" class="bg-accent text-accent-foreground px-4 py-2 rounded">导入</el-button> -->
      <el-button @click="exportData(vehicles, '应急处置方案管理', selectedIds)">导出</el-button>
    </div>

    <!-- Data Table -->
    <el-table v-loading="loading" :data="displayedVehicles" @selection-change="handleSelectionChange" style="width: 100%"
      ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle" :row-key="rowKey">
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column prop="ID" label="序号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="DISPOSAL_PLAN_CODE" label="处置方案编码" header-align="center" align="center"></el-table-column>


      <el-table-column prop="DISPOSAL_PLAN_NAME" label="处置方案名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="EVENT_NAME" label="事件名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="GEN_DATE" label="生成日期" header-align="center" align="center">
        <template #default="scope">
          {{ dayjs(scope.row.GEN_DATE).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>



      <el-table-column prop="ATTACHMENT" label="附件" header-align="center" align="center">
        <template #default="scope">

<div>{{ scope.row.ATTACHMENT }}</div>

        <el-button v-if="scope.row.ATTACHMENT!=null "  style="width: 75px; height: 30px;"
          @click="uploadfile(apiBaseUrl + '/download/' + scope.row.ATTACHMENT)">
          下载查看
        </el-button>

</template>
      </el-table-column>
      <el-table-column prop="ACCIDENT_CODE" label="关联事故编号" header-align="center" align="center"></el-table-column>


      <!-- <el-table-column label="操作" header-align="center" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editVehicle(scope.row)" link>编辑</el-button>
          <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- Pagination -->
    <Pagination v-if="vehicles.length" :tableData="vehicles" @alltabledata="alltabledata" />
    <!-- Add Vehicle Dialog -->
    <el-dialog width="600px" class="dialog-from" v-model="isAddDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'"
      destroy-on-close align-center :before-close="closeAddDialog">
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-6">
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">事故编号：</label>
              <el-input type="text" v-model="newVehicle.DISPOSAL_PLAN_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案编码：</label>
              <el-input type="text" v-model="newVehicle.EMERGENCE_PLAN_ID" required />

            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">应急资源编码：</label>
              <el-input type="text" v-model="newVehicle.MATERIAL_ID" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">应急队伍编码：</label>
              <el-input type="text" v-model="newVehicle.UNIT_ID" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">避难场所编码：</label>
              <el-input type="text" v-model="newVehicle.SHELTER_ID" required />

            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">机构编码：</label>
              <el-input type="text" v-model="newVehicle.INSTITUTION_ID" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">接警编码：</label>
              <el-input type="text" v-model="newVehicle.SERIAL_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">专家编码：</label>
              <el-input type="text" v-model="newVehicle.EXPERT_ID" required />

            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">事故日期时间：</label>
              <el-input type="datetime-local" v-model="newVehicle.ACCIDENT_TIME" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">事故概况：</label>
              <el-input type="text" v-model="newVehicle.ACCIDENT_OVERVIEW" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">现场图片：</label>
              <el-image v-if="isEditing" style=" width: 100px; height: 100px" lazy :src="newVehicle.imgdata"
                :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :initial-index="0" fit="cover" />
              <!-- :preview-src-list="newVehicle.imgdata" -->
              <input type="file" id="importFile" @change="handleRISK_HAS" accept=".jpg,.png,.jpeg"
                class="mt-1 block w-full">
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">总指挥：</label>
              <el-input type="text" v-model="newVehicle.GENERAL_COMMANDER" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">副总指挥：</label>
              <el-input type="text" v-model="newVehicle.DEPUTY_COMMANDER" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">现场指挥长：</label>
              <el-input type="text" v-model="newVehicle.ON_SITE_COMMANDER" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">现场副指挥长：</label>
              <el-input type="text" v-model="newVehicle.DEPUTY_ON_SITE_COMMANDER" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">现场响应小组：</label>
              <el-input type="text" v-model="newVehicle.RESPONSE_TEAM" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">现场处置措施建议：</label>
              <el-input type="text" v-model="newVehicle.DISPOSITION_GUIDANCE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">个体防护处置建议：</label>
              <el-input type="text" v-model="newVehicle.PERSONALPROTECTION_GUIDANCE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">其他注意事项：</label>
              <el-input type="text" v-model="newVehicle.NOTE" required />
            </div>
          </div>
        </div>
        <hr style="margin:8px" />
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click="addNewVehicle" style="width: 75px; height: 30px;">确认</el-button>
          <el-button @click="closeAddDialog" style="width: 75px; height: 30px;">取消</el-button>

        </div>
      </form>
    </el-dialog>
    <!-- Edit Vehicle Dialog -->
    <div v-if="isEditDialogOpen" class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">编辑车辆调度</h3>
          <button @click="closeEditDialog" class="text-gray-500 hover:text-gray-700">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <div class="mb-4">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="editVehicleCode" class="block text-sm font-medium text-gray-700">车辆编号：</label>
              <input type="text" id="editVehicleCode" v-model="editingVehicle.vehicle_code"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editVehicleType" class="block text-sm font-medium text-gray-700">车辆类型：</label>
              <select id="editVehicleType" v-model="editingVehicle.vehicle_type"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="消防车">消防车</option>
                <option value="救护车">救护车</option>
                <option value="指挥车">指挥车</option>
              </select>
            </div>
            <div>
              <label for="editLicensePlate" class="block text-sm font-medium text-gray-700">车牌号：</label>
              <input type="text" id="editLicensePlate" v-model="editingVehicle.vehicle_number"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editDeparturePoint" class="block text-sm font-medium text-gray-700">出发地点：</label>
              <input type="text" id="editDeparturePoint" v-model="editingVehicle.departure_point"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editDriverName" class="block text-sm font-medium text-gray-700">驾驶员姓名：</label>
              <input type="text" id="editDriverName" v-model="editingVehicle.driver_name"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editContactInfo" class="block text-sm font-medium text-gray-700">联系方式：</label>
              <input type="text" id="editContactInfo" v-model="editingVehicle.contact_info"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
              <label for="editDispatchStatus" class="block text-sm font-medium text-gray-700">出行状态：</label>
              <select id="editDispatchStatus" v-model="editingVehicle.dispatch_status"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="已出发">已出发</option>
                <option value="已返回">已返回</option>
              </select>
            </div>
            <div>
              <label for="editReturnTime" class="block text-sm font-medium text-gray-700">返回时间：</label>
              <input type="datetime-local" id="editReturnTime" v-model="editingVehicle.return_time"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
          </div>
        </div>

        <div class="flex justify-center space-x-2 mt-6">
          <button @click="updateVehicle"
            class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400">
            确认
          </button>
          <button @click="closeEditDialog"
            class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-400">
            取消
          </button>
        </div>
      </div>
    </div>

    <!-- View Vehicle Dialog -->
    <!-- <div v-if="isViewDialogOpen" class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">查看车辆调度详情</h3>
          <button @click="closeViewDialog" class="text-gray-500 hover:text-gray-700">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div v-for="(value, key) in viewingVehicle" :key="key" class="mb-2">
            <strong>{{ getChineseFieldName(key) }}:</strong> {{ value }}
          </div>
        </div>

        <div class="flex justify-center mt-6">
          <button @click="closeViewDialog"
            class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-400">
            关闭
          </button>
        </div>
      </div>
    </div> -->
    <el-dialog width="1000px" class="dialog-from" v-model="isViewDialogOpen" title="查看详情" destroy-on-close align-center
      :before-close="closeViewDialog">
      <div class="body-item">
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="box-content">
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">事故编号:</span>
                <span class="auto-wrap">{{ viewingVehicle.DISPOSAL_PLAN_CODE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">预案编码:</span>
                <span class="auto-wrap">{{ viewingVehicle.EMERGENCE_PLAN_ID }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">应急资源编码:</span>
                <span class="auto-wrap">{{ viewingVehicle.MATERIAL_ID }}</span>
              </div>
            </el-col>

          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">应急队伍编码:</span>
                <span class="auto-wrap">{{ viewingVehicle.UNIT_ID }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">避难场所编码:</span>
                <span class="auto-wrap">{{ viewingVehicle.SHELTER_ID }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">机构编码:</span>
                <span class="auto-wrap">{{ viewingVehicle.INSTITUTION_ID }}</span>
              </div>
            </el-col>

          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">接警编码:</span>
                <span class="auto-wrap">{{ viewingVehicle.SERIAL_CODE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">专家编码:</span>
                <span class="auto-wrap">{{ viewingVehicle.EXPERT_ID }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">事故日期时间:</span>
                <span class="auto-wrap">{{ dayjs(viewingVehicle.ACCIDENT_TIME).format('YYYY-MM-DD HH:mm:ss') }}</span>
              </div>
            </el-col>

          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">事故概况:</span>
                <span class="auto-wrap">{{ dayjs(viewingVehicle.ACCIDENT_OVERVIEW).format('YYYY-MM-DD') }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <div class="no-wrap">现场图片:</div>
                <el-image style="width: 100px; height: 100px" lazy :src="viewingVehicle.imgdata" :zoom-rate="1.2"
                  :max-scale="7" :min-scale="0.2" :initial-index="0" fit="cover" />
                <!-- :preview-src-list="imgdata" -->
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">总指挥:</span>
                <span class="auto-wrap">{{ viewingVehicle.GENERAL_COMMANDER }}</span>
              </div>
            </el-col>

          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">副总指挥:</span>
                <span class="auto-wrap">{{ viewingVehicle.GENERAL_COMMANDER }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">现场指挥长:</span>
                <span class="auto-wrap">{{ viewingVehicle.ON_SITE_COMMANDER }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">现场副指挥长:</span>
                <span class="auto-wrap">{{ viewingVehicle.DEPUTY_ON_SITE_COMMANDER }}</span>
              </div>
            </el-col>

          </el-row>

          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="19">
              <div>
                <span class="no-wrap">现场响应小组:</span>
                <span class="auto-wrap">{{ viewingVehicle.RESPONSE_TEAM }}</span>
              </div>
            </el-col>
            <el-col style="visibility: hidden;" :span="1">
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="19">
              <div>
                <span class="no-wrap">现场处置措施建议:</span>
                <span class="auto-wrap">{{ viewingVehicle.DISPOSITION_GUIDANCE }}</span>
              </div>
            </el-col>
            <el-col style="visibility: hidden;" :span="1">

            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="19">
              <div>
                <span class="no-wrap">个体防护处置建议:</span>
                <span class="auto-wrap">{{ viewingVehicle.PERSONALPROTECTION_GUIDANCE }}</span>
              </div>
            </el-col>
            <el-col style="visibility: hidden;" :span="1">

            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="19">
              <div>
                <span class="no-wrap">其他注意事项:</span>
                <span class="auto-wrap">{{ viewingVehicle.NOTE }}</span>
              </div>
            </el-col>
            <el-col style="visibility: hidden;" :span="1">

            </el-col>
          </el-row>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeViewDialog">
            确定
          </el-button>
          <el-button @click="closeViewDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- Import Dialog -->
    <div v-if="isImportDialogOpen"
      class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[400px]">
        <h3 class="text-lg font-bold mb-4">导入车辆信息</h3>
        <div class="mb-4">
          <label for="importFile" class="block text-sm font-medium text-gray-700">选择文件</label>
          <input type="file" id="importFile" @change="handleFileUpload" accept=".csv, .xlsx" class="mt-1 block w-full">
        </div>
        <div class="mt-4 flex justify-end space-x-2">
          <button @click="closeImportDialog"
            class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded">取消</button>
          <button @click="confirmImport"
            class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">确认导入</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import { dayjs } from "element-plus"
const apiBaseUrl = ref(proxy.$currentUrl + '/api/disposal_plan')
import { exportData, uploadfile,checkval } from '#/utils/exportfile.js'
// 搜索相关
const search = ref({
  DISPOSAL_PLAN_CODE: '',
  EMERGENCE_PLAN_ID: '',

})
const formItems = ref([
  {
    label: '处置方案编码：',
    model: 'DISPOSAL_PLAN_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  // {
  //   label: '预案编码：',
  //   model: 'EMERGENCE_PLAN_ID',
  //   type: 'input',
  //   placeholder: '请输入',
  // },


])
const loading = ref(false)
// 数据相关
const imgdata = ref('')
const vehicles = ref([])
const allChecked = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])
const rowKey = (row) => row.ID // 设置行的唯一标识
// 对话框状态
const isAddDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isEditing = ref(false)
// 新增车辆数据
const newVehicle = ref({
  files: []
})
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
// 编辑和查看车辆数据
const editingVehicle = ref({})
const viewingVehicle = ref({})
const table = ref()
// 计算属性
const totalItems = computed(() => vehicles.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)
const endIndex = computed(() =>
  Math.min(startIndex.value + pageSize.value, totalItems.value),
)
const displayedVehicles = ref([])
const alltabledata = (data) => {
  displayedVehicles.value = data
  
}
// API 用函数
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}

const handleRISK_HAS = (event) => {
  newVehicle.value.files[0] = []
  const files = Array.from(event.target.files)

  newVehicle.value.files[0] = files[0]
}


const searchVehicles = async () => {
  displayedVehicles.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })

    vehicles.value=response.data
    // vehicles.value = (await Promise.all(response.data.map(async (item) => {
    //   const resimg = await axios.get(`${apiBaseUrl.value}/${item.ANNEX}`)
    //   return { ...item, checked: false, imgdata: resimg.data.url }
    // })))
  } catch (error) {
    console.error('搜索失败:', error)
    if (error.response && error.response.status === 404) {
      alert('没有记录')
    } else {
      alert('搜索失败: ' + (error.response?.data?.message || error.message))
    }
  }
}
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}



const addNewVehicle = async () => {
  // if (checkval([
  //   'DISPOSAL_PLAN_CODE',
  //   'EMERGENCE_PLAN_ID',
  //   'MATERIAL_ID',
  //   'UNIT_ID',
  //   'SHELTER_ID',
  //   'INSTITUTION_ID',
  //   'SERIAL_CODE',
  //   'EXPERT_ID',
  //   'ACCIDENT_TIME',
  //   'ACCIDENT_OVERVIEW',
  //   'GENERAL_COMMANDER',
  //   'DEPUTY_COMMANDER',
  //   'ON_SITE_COMMANDER',
  //   'DEPUTY_ON_SITE_COMMANDER',
  //   'RESPONSE_TEAM',
  //   'DISPOSITION_GUIDANCE',
  //   'PERSONALPROTECTION_GUIDANCE'

  // ], '应急处置记录方案管理', newVehicle.value)) {
  //   return
  // }

  if (!newVehicle.value.files) {
    alert('现场图片不能为空')
    return
  }



  const formData = new FormData()
  newVehicle.value.ACCIDENT_TIME = dayjs(newVehicle.value.ACCIDENT_TIME).format('YYYY-MM-DDTHH:mm')
  for (const key in newVehicle.value) {
    if (key != 'files') {
      formData.append(key, newVehicle.value[key])
    }
  }
  if (newVehicle.value?.files) {
    newVehicle.value.files.forEach((file, index) => {
      formData.append(`files[${index}]`, file)
    })
  }


  try {
    if (!isEditing.value) {
      await axios.post(apiBaseUrl.value, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      alert('创建成功')
    } else {
      await axios.put(`${apiBaseUrl.value}/${newVehicle.value.ID}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      alert('更新成功')
    }
    closeAddDialog()
    await searchVehicles()
  } catch (error) {
    console.error('创建失败:', error)
    alert('创建失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {

  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(item =>
        axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      ))
      selectedIds.value = []
      alert('删除成功')
      table.value.clearSelection()
      await searchVehicles()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// const exportData = async () => {
//   try {
//     const response = await axios.get(`${apiBaseUrl.value}/export`, { responseType: 'blob' })
//     const url = window.URL.createObjectURL(new Blob([response.data]))
//     const link = document.createElement('a')
//     link.href = url
//     link.setAttribute('download', '车辆信息.xlsx')
//     document.body.appendChild(link)
//     link.click()
//   } catch (error) {
//     console.error('导出失败:', error)
//     alert('导出失败: ' + (error.response?.data?.message || error.message))
//   }
// }

// 事件处理函数
const resetSearch = () => {
  search.value = {
    DISPOSAL_PLAN_CODE: '',
    EMERGENCE_PLAN_ID: '',
  }
  searchVehicles()
}

const toggleAllCheckboxes = () => {
  vehicles.value.forEach(vehicle => vehicle.checked = allChecked.value)
}

const openAddDialog = () => {
  isAddDialogOpen.value = true
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  newVehicle.value = {
    files: []
  }
  isEditing.value = false
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const handleFileUpload = (event) => {
  // 处理文件上传逻辑
}

const confirmImport = async () => {
  try {
    const formData = new FormData()
    formData.append('file', document.getElementById('importFile').files[0])

    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    alert(response.data.message || '导入成功')
    closeImportDialog()
    await searchVehicles()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
}

const editVehicle = (vehicle) => {

  newVehicle.value = { ...vehicle }
  newVehicle.value.ACCIDENT_TIME = dayjs(newVehicle.value.ACCIDENT_TIME).format('YYYY-MM-DD HH:mm:ss')
  newVehicle.value.files = []
  isAddDialogOpen.value = true
  isEditing.value = true
}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
  editingVehicle.value = {}
}

const updateVehicle = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${editingVehicle.value.id}`, editingVehicle.value)
    alert(response.data.message || '更新成功')
    closeEditDialog()
    await searchVehicles()
  } catch (error) {
    console.error('更新失败:', error)
    alert('更新失败: ' + (error.response?.data?.message || error.message))
  }
}

const viewDetails = (vehicle) => {
  viewingVehicle.value = { ...vehicle }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingVehicle.value = {}
}

// 获取中文字段名
const getChineseFieldName = (key) => {
  const fieldNameMap = {
    vehicle_code: '车辆编号',
    vehicle_type: '车辆类型',
    license_plate: '车牌号',
    departure_point: '出发地点',
    driver_name: '驾驶员姓名',
    contact_info: '联系方式',
    dispatch_status: '出行状态',
    return_time: '返回时间'
  }
  return fieldNameMap[key] || key
}

// 生命周期钩子
onMounted(() => {
  searchVehicles()
})
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>
